//
//  WeatherDataManager.m
//  DayDayRun
//
//  Created by 卫建 on 16/1/7.
//  Copyright © 2016年 卫建. All rights reserved.
//

#import "WeatherDataManager.h"
#import "WeatherModel.h"
//#import "JSONKit.h"
#import "WeatherModel.h"
static WeatherDataManager *weatherDataManager = nil;
@implementation WeatherDataManager


+(instancetype)sharedWeatherDataManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        if (weatherDataManager == nil)
        {
            weatherDataManager = [[WeatherDataManager alloc]init];
        }
        
    });
    
    return weatherDataManager;
}



#pragma mark-------请求天气数据的方法
-(void)getWeatherDataManager:(WeatherBlock)finishBlock
{
    //获取网址字符串
    NSString *string = [NSString stringWithFormat:@"http://wthrcdn.etouch.cn/weather_mini?citykey=101010100"];
//#warning 先赋值初始化的城市
    
    NSURL *url = [NSURL URLWithString:string];
    
    //创建网络请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //发送网络请求
    NSURLSession *session = [NSURLSession sharedSession];
    
    //发送
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
        @autoreleasepool
        {
         
            if (data == nil || error != nil)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    return finishBlock(NO);
                    
                });
            }
            
            //解析数据
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSDictionary *dataDict = resultDict[@"data"];
            
            //拿出forecast
            NSArray *forecastArray = dataDict[@"forecast"];
            
            //遍历
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:6];
            
            for (NSDictionary *dict in forecastArray)
            {
                WeatherModel *model = [[WeatherModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                [array addObject:model];
            }
            
            self.weatherArray = [NSArray arrayWithArray:array];
            
            //回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
               
                //调用block
                finishBlock(self.weatherArray.count > 0);
                
            });
            
        }
        
    }];
    
    //开始请求任务
    [task resume];
}

@end
